package com.coldchain.cys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coldchain.common.msg.BaseResponse;
import com.coldchain.common.msg.ObjectRestResponse;
import com.coldchain.cys.constant.Constant;
import com.coldchain.cys.context.CysContext;
import com.coldchain.cys.entity.SysMessage;
import com.coldchain.cys.mapper.SysMessageMapper;
import com.coldchain.cys.page.SysMessageQueryVo;
import com.coldchain.cys.service.ISysMessageService;
import com.fangliai.core.context.BaseContextHandler;
import com.fangliai.core.entitiy.SystemModelEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianpeng
 * @since 2018-08-28
 */
@Service
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage> implements ISysMessageService {

	@Transactional
	@Override
	public BaseResponse pushCysMessage(SysMessage sysMessage) {
		if(sysMessage.getCid() == null){
			return getErrorResponse("推送的消息承运商id不能为空") ;
		}
		if(StringUtils.isEmpty(sysMessage.getTitle())){
			return getErrorResponse("推送的消息标题不能为空") ;
		}
		if(StringUtils.isEmpty(sysMessage.getContent())){
			return getErrorResponse("推送的消息内容不能为空") ;
		}
		sysMessage.setInreader(Constant.SYS_MESSAGE_UNREAD);
		sysMessage.setCreatetime(new Date());
		
		boolean flag = super.save(sysMessage) ;
		if(!flag){
			return getErrorResponse("推送消息失败") ;
		}
		return new ObjectRestResponse<>().succeed("消息推送成功") ;
	}

	@Override
	public void getCysMessageList(SysMessageQueryVo vo) {
		String sysModel = BaseContextHandler.getSysModl();
		if(sysModel.equals(SystemModelEnum.CYS.name())) {
			//承运商模块
			Long cysId = CysContext.getCysID();
			vo.setCid(cysId); 
		}
		QueryWrapper<SysMessage> ew = new QueryWrapper<SysMessage>();
		if(vo.getCid() != null) {
			ew.eq("cid", vo.getCid()) ;
		}
		ew.orderByDesc("createtime") ;
		super.page(vo,ew);
	}

	@Override
	public SysMessage getCysMessageDetail(Integer id) {
		Long cysid = CysContext.getCysID();
		QueryWrapper<SysMessage> ew = new QueryWrapper<SysMessage>();
		ew.eq("id", id);
		ew.eq("cid", cysid) ;
		return super.getOne(ew) ;
	}

	private BaseResponse getErrorResponse(String msg) {
		return new ObjectRestResponse<>().error(msg) ;
	}
}
